package com.lei.springbootpractice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 数据库性能配置类
 * 用于监控和优化H2数据库性能
 */
@Configuration
public class DatabasePerformanceConfig {

    /**
     * 初始化数据库性能设置
     */
    @Bean
    @Profile("!prod") // 仅在非生产环境启用
    public DatabasePerformanceMonitor databasePerformanceMonitor(DataSource dataSource) {
        return new DatabasePerformanceMonitor(dataSource);
    }

    public static class DatabasePerformanceMonitor {
        private final DataSource dataSource;

        public DatabasePerformanceMonitor(DataSource dataSource) {
            this.dataSource = dataSource;
            initializePerformanceSettings();
        }

        private void initializePerformanceSettings() {
            try (Connection connection = dataSource.getConnection()) {
                // 只应用最基本和兼容的H2设置
                executeUpdateSafely(connection, "SET CACHE_SIZE 8192"); // 增加缓存大小
                executeUpdateSafely(connection, "SET LOCK_TIMEOUT 10000"); // 设置锁超时
                
                System.out.println("H2数据库性能优化设置已应用");
            } catch (SQLException e) {
                System.err.println("无法获取数据库连接进行性能设置: " + e.getMessage());
            }
        }

        private void executeUpdateSafely(Connection connection, String sql) {
            try (PreparedStatement stmt = connection.prepareStatement(sql)) {
                stmt.executeUpdate();
                System.out.println("✓ 执行成功: " + sql);
            } catch (SQLException e) {
                System.out.println("✗ 执行失败: " + sql + " - " + e.getMessage());
                // 不抛出异常，继续执行其他设置
            }
        }
    }
} 